<template>
  <view class="energy-container">
    <view class="form-content">
      <view class="form-title flex align-item-center">
        <view class="line"></view>能源站信息
        <view class="ml-20" v-if="boilerRoomForm.updateType"
          ><up-tag
            size="mini"
            :text="boilerRoomForm.updateType"
            plain
            plainFill
          >
          </up-tag
        ></view>
      </view>
      <view
        class="checkStatus"
        v-if="boilerRoomForm.checkStatus"
        :class="{ warnColor: boilerRoomForm.checkStatus == '审核不通过' }"
      >
        {{ boilerRoomForm.checkStatus }}
      </view>
      <up-form
        labelPosition="left"
        :model="boilerRoomForm"
        ref="energyStationRef"
        labelWidth="110px"
      >
        <up-form-item label="能源站名称" prop="name" borderBottom required>
          <up-textarea
            v-model="boilerRoomForm.name"
            border="none"
            placeholder="请输入能源站名称"
            autoHeight
          ></up-textarea>
        </up-form-item>
        <up-form-item label="能源站简称" prop="shortName" borderBottom>
          <up-textarea
            v-model="boilerRoomForm.shortName"
            placeholder="请输入能源站简称"
            border="none"
            autoHeight
          ></up-textarea>
        </up-form-item>
        <up-form-item
          label="省市区"
          prop="cityAllName"
          borderBottom
          @click="openCityPicker()"
        >
          <up-input
            v-model="boilerRoomForm.cityAllName"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择省市县"
            border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-down"></up-icon>
          </template>
        </up-form-item>

        <up-picker
          :show="cityShow"
          ref="uPickerRef"
          :columns="cityArr"
          keyName="label"
          @change="changeHandler"
          @confirm="onCityConfirm"
          @cancel="cityShow = false"
        ></up-picker>

        <up-form-item label="街道" prop="street" borderBottom>
          <up-textarea
            v-model="boilerRoomForm.street"
            placeholder="请输入街道"
            autoHeight
            border="none"
          ></up-textarea>
        </up-form-item>
        <up-form-item label="详细地址" prop="adress" borderBottom>
          <up-textarea
            v-model="boilerRoomForm.adress"
            placeholder="请输入详细地址"
            autoHeight
            border="none"
          ></up-textarea>
        </up-form-item>
        <!-- <up-form-item label="联系人" borderBottom required prop="contacts">
					<up-input v-model="boilerRoomForm.contacts" placeholder="请输入联系人" border="none"></up-input>
				</up-form-item>
				<up-form-item :label="'联系电话'" borderBottom required prop="contactNumber">
					<up-input v-model="boilerRoomForm.contactNumber" placeholder="请输入联系电话" border="none"></up-input>
				</up-form-item> -->

        <view v-for="(item, index) in boilerRoomForm.contactsArr" :key="index">
          <up-form-item
            :label="'联系人'"
            borderBottom
            :prop="`contactsArr.${index}.user`"
          >
            <up-input
              v-model="item.user"
              placeholder="请输入联系人"
              border="none"
            ></up-input>
            <template #right>
              <up-button
                v-if="index === 0"
                size="small"
                type="primary"
                :plain="true"
                shape="circle"
                @click="addUser"
                >添加联系人</up-button
              >
              <up-button
                v-else
                size="small"
                type="error"
                :plain="true"
                shape="circle"
                @click="delUser(index)"
                >删除联系人</up-button
              >
            </template>
          </up-form-item>
          <up-form-item
            :label="'联系电话'"
            borderBottom
            :prop="`contactsArr.${index}.tel`"
          >
            <up-input
              v-model="item.tel"
              placeholder="请输入联系电话"
              border="none"
            ></up-input>
          </up-form-item>
        </view>

        <up-form-item
          label="主行业类别"
          prop="industryType"
          borderBottom
          @click="handleFormItemClick('industryType')"
        >
          <up-input
            v-model="boilerRoomForm.industryType"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择主行业类别"
            border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-down"></up-icon>
          </template>
        </up-form-item>

        <up-form-item
          label="主行业代码"
          prop="industryCode"
          borderBottom
          @click="handleFormItemClick('industryCode')"
        >
          <up-input
            v-model="boilerRoomForm.industryCode"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择主行业代码"
            border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-down"></up-icon>
          </template>
        </up-form-item>

        <up-picker
          :show="industryCodeShow"
          :defaultIndex="industryIdx"
          :keyName="industryKey"
          :columns="[industryCodeArr]"
          @confirm="industryCodeSelect"
          @cancel="industryCancel"
        ></up-picker>

        <up-form-item
          label="管理类别"
          prop="managesType"
          borderBottom
          @click="handleManagesTypeClick()"
        >
          <up-input
            v-model="boilerRoomForm.managesType"
            disabled
            disabled-color="#ffffff"
            placeholder="请选择管理类别"
            border="none"
          ></up-input>
          <template #right>
            <up-icon name="arrow-down"></up-icon>
          </template>
        </up-form-item>
        <up-picker
          :show="managesTypeShow"
          :defaultIndex="managesTypeIdx"
          :columns="[managesTypeArr]"
          @confirm="managesTypeSelect"
          @cancel="
            managesTypeShow = false;
            managesTypeIdx = [0];
          "
        ></up-picker>

        <up-form-item label="排污许可证编号" prop="licenceNumber" borderBottom>
          <up-input
            v-model="boilerRoomForm.licenceNumber"
            placeholder="请输入排污许可证编号"
            border="none"
          ></up-input>
        </up-form-item>

        <up-form-item
          label="地理坐标"
          prop="latLon"
          borderBottom
          @click="handleOpenMap"
        >
          <up-input
            v-model="boilerRoomForm.latLon"
            disabled
            disabledColor="#ffffff"
            placeholder="请获取坐标"
            border="none"
          ></up-input>
          <template #right>
            <up-icon name="map-fill" size="24" color="#246eff"></up-icon>
          </template>
        </up-form-item>

        <up-form-item label="上传图片">
          <up-upload
            :fileList="boilerRoomForm.image"
            @afterRead="afterRead"
            @delete="deletePic"
            :previewFullImage="true"
            name="1"
            multiple
            :maxCount="3"
          ></up-upload>
        </up-form-item>
      </up-form>
      <view class="bottom-btn">
        <up-button
          type="primary"
          color="#246eff"
          shape="circle"
          @click="handleSave()"
          >保存</up-button
        >
      </view>
    </view>
  </view>
</template>

<script>
import {
  generateId,
  addSaveEnergyStation,
  getEnergyStationInfo,
  getDictList,
  uploadImg,
  deleteImg,
} from '@/api/company';
import { areaData } from '../../common/cityData';

export default {
  data() {
    return {
      dialogType: 'add',
      boilerRoomForm: {
        companyId: '',
        name: '',
        shortName: '',
        cityAllName: '',
        province: '',
        city: '',
        county: '',
        street: '',
        adress: '',
        longitude: '',
        latitude: '',
        contacts: '',
        contactNumber: '',
        contactsArr: [
          {
            user: '',
            tel: '',
          },
        ],
        industryType: '',
        industryCode: '',
        managesType: '',
        licenceNumber: '',
        latLon: '', //经纬度
        image: [],
      },
      rules: {
        name: [
          {
            required: true,
            message: '请填写能源站名称',
            trigger: ['blur', 'change'],
          },
        ],
      },
      cityShow: false,
      cityArr: [[], [], []],
      industryKey: 'mainIndustry',
      industryIdx: [],
      industryCodeShow: false,
      industryCodeArr: [],
      managesTypeShow: false,
      managesTypeIdx: [],
      managesTypeArr: [],
    };
  },
  onLoad(options) {
    this.initData(options);
  },
  mounted() {
    this.$refs.energyStationRef.setRules(this.rules);
    // const index = 0;
    // this.rules[`contactsArr.${index}.user`] = [{
    // 	required: true,
    // 	message: '联系人不能为空',
    // 	trigger: 'blur',
    // }, ];
    // this.rules[`contactsArr.${index}.tel`] = [{
    // 		required: true,
    // 		message: '手机号不能为空',
    // 		trigger: 'blur',
    // 	},
    // 	{
    // 		validator: (rule, value, callback) => {
    // 			return uni.$u.test.mobile(value);
    // 		},
    // 		message: '手机号码不正确',
    // 		trigger: ['change', 'blur'],
    // 	},
    // ];
  },
  methods: {
    async initData(options) {
      const { type, stationInfo } = options;
      this.dialogType = type;
      uni.setNavigationBarTitle({
        title: type == 'add' ? '添加能源站' : '能源站详情',
      });
      let energyStationObj = JSON.parse(decodeURIComponent(stationInfo));
      if (type == 'add') {
        const { companyId, province, city, county, areaName } =
          energyStationObj;
        this.boilerRoomForm.companyId = companyId;
        this.boilerRoomForm.province = province;
        this.boilerRoomForm.city = city;
        this.boilerRoomForm.county = county;
        this.boilerRoomForm.cityAllName = areaName;
      } else {
        const res = await getEnergyStationInfo(energyStationObj.id, {
          checkTag: 1,
        });
        const {
          longitude,
          latitude,
          province,
          city,
          county,
          contacts,
          contactNumber,
        } = res;
        this.boilerRoomForm = {
          ...res,
        };
        this.boilerRoomForm.latLon =
          longitude && latitude ? `${latitude},${longitude}` : '';
        this.boilerRoomForm.cityAllName =
          province && city && county ? `${province}/${city}/${county}` : '';
        const userArr = contacts.split(',');
        const telArr = contactNumber.split(',');

        const contactList = userArr.map((item, index) => {
          return {
            user: item,
            tel: telArr[index],
          };
        });
        this.boilerRoomForm.contactsArr =
          contactList.length > 0
            ? contactList
            : [
                {
                  user: '',
                  tel: '',
                },
              ];
        this.boilerRoomForm.image = res.image === null ? [] : res.image;
      }
    },
    /**打开省市县**/
    openCityPicker() {
      this.cityArr[0].push(...areaData);
      this.cityArr[1].push(...this.cityArr[0][0].children);
      this.cityArr[2].push(...this.cityArr[1][0].children);
      this.cityShow = true;
    },
    changeHandler(e) {
      const { columnIndex, value } = e;
      let city = value[0].children;
      if (columnIndex === 0) {
        this.$refs.uPickerRef.setColumnValues(1, city);
        this.$refs.uPickerRef.setColumnValues(2, city[0].children);
      } else if (columnIndex === 1) {
        this.$refs.uPickerRef.setColumnValues(2, value[1].children);
      }
    },
    onCityConfirm(e) {
      const { value } = e;
      this.boilerRoomForm.province = value[0].label;
      this.boilerRoomForm.city = value[1].label;
      this.boilerRoomForm.county = value[2].label;
      this.boilerRoomForm.cityAllName = `${value[0].label}/${value[1].label}/${value[2].label}`;
      this.cityShow = false;
      // this.$refs.energyStationRef.validateField('cityAllName');
    },
    industryCodeSelect(e) {
      const { indexs, value } = e;
      this.boilerRoomForm.industryType = value[0].mainIndustry;
      this.boilerRoomForm.industryCode = value[0].code;
      this.industryCodeShow = false;
    },
    managesTypeSelect(e) {
      const { indexs, value } = e;
      this.boilerRoomForm.managesType = value[0];
      this.managesTypeShow = false;
    },
    /*打开picker*/
    async handleFormItemClick(name) {
      this.industryKey = name == 'industryType' ? 'mainIndustry' : 'code';
      const data = await getDictList('1865031771868000012');
      if (this.boilerRoomForm[name]) {
        const value = this.boilerRoomForm[name];
        const idx = data.findIndex((item) => item[this.industryKey] === value);
        this.industryIdx = [idx];
      } else {
        this.industryIdx = [0];
      }
      this.industryCodeArr = data;
      this.industryCodeShow = true;
    },
    industryCancel() {
      this.industryIdx = [0];
      this.industryCodeShow = false;
    },
    /**添加联系人**/
    addUser() {
      this.boilerRoomForm.contactsArr.push({
        user: '',
        tel: '',
      });
      // const {
      // 	contactsArr
      // } = this.boilerRoomForm;
      // contactsArr.forEach((item, index) => {
      // 	this.rules[`contactsArr.${index}.user`] = [{
      // 		required: true,
      // 		message: '联系人不能为空',
      // 		trigger: 'blur'
      // 	}, ];
      // 	this.rules[`contactsArr.${index}.tel`] = [{
      // 			required: true,
      // 			message: '手机号不能为空',
      // 			trigger: 'blur'
      // 		},
      // 		{
      // 			validator: (rule, value, callback) => {
      // 				return uni.$u.test.mobile(value);
      // 			},
      // 			message: '手机号码不正确',
      // 			trigger: ['change', 'blur'],
      // 		},
      // 	];
      // });
    },
    /**删除联系人**/
    delUser(index) {
      this.boilerRoomForm.contactsArr.splice(index, 1);
      // 同步删除掉新增子项时 rules 对象中添加的校验规则
      // delete this.rules[`contactsArr.${index}.user`];
      // delete this.rules[`contactsArr.${index}.tel`];
    },
    /**打开管理类别**/
    async handleManagesTypeClick() {
      const list = await getDictList('1865031771868000013');
      this.managesTypeArr = list;
      const { managesType } = this.boilerRoomForm;
      if (managesType !== '') {
        const midx = list.findIndex((item) => item === managesType);
        this.managesTypeIdx = [midx];
      } else {
        this.managesTypeIdx = [0];
      }
      this.managesTypeShow = true;
    },

    /**打开地图**/
    handleOpenMap() {
      const { longitude, latitude } = this.boilerRoomForm;
      uni.chooseLocation({
        longitude: longitude || '',
        latitude: latitude || '',
        success: (res) => {
          this.boilerRoomForm.latLon = `${res.latitude},${res.longitude}`;
          this.boilerRoomForm.latitude = res.latitude;
          this.boilerRoomForm.longitude = res.longitude;

          console.log('纬度：' + res.latitude);
          console.log('经度：' + res.longitude);
        },
        fail: (err) => {
          console.error(err, '获取位置失败');
        },
      });
    },
    /**上传图片**/
    async afterRead(event) {
      let lists = [].concat(event.file);
      let energyStationId = await generateId({});
      let fileListLen = this.boilerRoomForm.image.length;
      lists.forEach((item) => {
        this.boilerRoomForm.image.push({
          url: item.url,
          size: item.size,
          status: 'uploading',
          message: '上传中',
        });
      });

      for (let i = 0; i < lists.length; i++) {
        const result = await uploadImg(lists[i].url, {
          stationId: energyStationId,
        });

        let item = this.boilerRoomForm.image[fileListLen];
        this.boilerRoomForm.image.splice(
          fileListLen,
          1,
          Object.assign(
            {
              url: item.url,
              size: item.size,
            },
            {
              status: 'success',
              message: '',
              ...result,
            }
          )
        );
        fileListLen++;
      }
    },

    /**删除图片**/
    async deletePic(event) {
      const { index, file } = event;
      const res = await deleteImg({
        filePath: file.url,
      });
      uni.showToast({
        title: '删除照片成功！',
      });
      this.boilerRoomForm.image.splice(index, 1);
    },
    /**
     * 保存
     */
    handleSave() {
      this.$refs.energyStationRef
        .validate()
        .then((valid) => {
          if (valid) {
            const { contactsArr } = this.boilerRoomForm;
            const params = {
              ...this.boilerRoomForm,
            };
            const userArr = contactsArr
              .map((person) => person.user)
              .filter((item) => item);
            params.contacts = userArr.length != 0 ? userArr.join(',') : '';
            const telArr = contactsArr
              .map((item) => item.tel)
              .filter((item) => item);
            params.contactNumber = telArr.length != 0 ? telArr.join(',') : '';
            delete params.cityAllName;
            delete params.latLon;
            delete params.contactsArr;

            addSaveEnergyStation(params).then((res) => {
              uni.$u.toast(this.dialogType == 'add' ? '添加成功' : '保存成功');
              setTimeout(() => {
                getApp().globalData.energyStationInfo = res || {};
                const stationInfo = res || {};
                uni.switchTab({
                  url: '/pages/index/index',
                });
              }, 1000);
            });
          } else {
            uni.$u.toast('校验失败');
          }
        })
        .catch(() => {
          // 处理验证错误
          uni.$u.toast('校验失败');
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.energy-container {
  width: 100%;
  min-height: 100vh;
  padding: 30rpx 20rpx 200rpx 20rpx;
  box-sizing: border-box;
  position: relative;
  background: #f8f8f8;
}

.form-content {
  padding: 20rpx;
  box-sizing: border-box;
  background: #fff;
  border-radius: 12rpx;
  position: relative;
  .form-title {
    font-size: 34rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    .line {
      width: 5px;
      height: 15px;
      border-radius: 10px;
      display: inline-block;
      margin-right: 20rpx;
      vertical-align: -2rpx;
      background-color: #0e8fe5;
    }
  }
  .checkStatus {
    position: absolute;
    right: 0;
    top: 0;
    padding: 12rpx 20rpx;
    background-color: #f60;
    font-size: 25rpx;
    color: #fff;
    font-weight: bold;
    border-radius: 4rpx 12rpx 4rpx 12rpx;
    &.warnColor {
      background-color: #f56c6c;
    }
  }
}

.bottom-btn {
  width: 100%;
  position: fixed;
  bottom: 0;
  padding: 40rpx 30rpx;
  left: 0;
  box-sizing: border-box;
  background: #fff;
  border-top: 1px solid #f4f4f4;
  z-index: 100;
}
</style>
<style>
.energy-container .u-textarea {
  padding: 9px 0 !important;
}

.energy-container .u-textarea__field {
  color: #303133 !important;
  min-height: 20px !important;
}
</style>
